import { useState, useEffect, useContext, useRef } from 'react'
import useBusinessMap from '../../../../../../common/BusinessMap/useBusinessMap';
import DarkCard from '../../../../../../common/DarkCard';
import { Button, Descriptions, Divider, Form, InputNumber, Radio, Space, Table, DatePicker, Tabs ,Tooltip} from 'antd';
import GlobalContext from '../../../../../../../utils/GlobalContext';
import { CloseOutlined } from '@ant-design/icons';
import PanelRight from '../../../../../../common/PanelRight';
import LittleTitle from '../../../../../../common/LittleTitle';
import { resourcePath } from '../../../../../../../utils/resource';
import { drawCircle, wktToGeom } from '../../../../../../../utils/helper/mapHelper';
import CztApi from '../../../../../../../utils/apis/CztApi';
import JzzyApi from '../../../../../../../utils/apis/JzzyApi';
import { fromCircle } from 'ol/geom/Polygon';
import JcyjApi from '../../../../../../../utils/apis/JcyjApi';
import ScrollTable from '../../../../../../common/ScrollTable';
import jcyjContext from '../../jcyjContext';
import LineChart from '../../ZheXianTu';
import rangeDisplayIcon from '../../rangeDisplayIcon';
import FetchHelper from '../../../../../../../utils/helper/fetch-helper';
import VideoMonitor from '../VideoMonitor';
export default function YqDetail(props) {
    const [data, setData] = useState();
    const [total, setTotal] = useState();
    const map = useBusinessMap();
    const { item } = props;
    const { setJcDates } = useContext(jcyjContext);
    const [jcdata, setJcdata] = useState();

    const [radius, setRadius] = useState();
    const [ypType, setYpType] = useState(1);
    const [yqList, setYqList] = useState();
    const [yxList, setYxList] = useState();
    // console.log('yxList',yxList)
    const [params, setParams] = useState({
        pageNum: 1,
        pageSize: 5,
        type:'降雨量'
    });

    //向父组件返回数据
    const [data1, setData1] = useState();
    const { setDatas1, setDatas2, setDatas3 } = props
    const handleButtonClick = (record) => {
        // 根据 record 中的数据执行相应的操作
        // console.log('点击了按钮，当前行数据：', record);
        setDatas1(record.name);
        setDatas2(data1);
        setDatas3(ypType);
    };




    const rootRef = useRef();
    const { RangePicker } = DatePicker;
    function Jygct() {
        return <>
            <Form className='fill h0' style={{
                marginTop: 10
            }}>
                <Form.Item>
                    <RangePicker />
                </Form.Item>
            </Form>

        </>
    }
    const [currentPanel, setCurrentPanel] = useState(1);
    const handlePanelChange = e => {
        setCurrentPanel(e.target.value);
    }
    // eslint-disable-next-line
    useEffect(() => {
        if (ypType && map && radius && item) {
            const center = wktToGeom(item.geom).getCoordinates();
            const circle = drawCircle(map, center, radius);
            setData1(circle)

            if (ypType === 1) {
                CztApi.listByPolygon(fromCircle(circle)).then(resp => {
                    setYxList(resp.data)
                     /* 
                    --rangeDisplayIcon是加载画圆范围内图标显示
                    */
                    rangeDisplayIcon(resp.data,circle,map,ypType,'nowkt');
                })
            } else {
                JzzyApi.listByPolygon(fromCircle(circle)).then(resp => {
                    setYxList(resp.data)
                     /* 
                    --rangeDisplayIcon是加载画圆范围内图标显示
                    */
                    rangeDisplayIcon(resp.data,circle,map,ypType,'nowkt');
                })
            }
        }
        return () => {
            const allLayers = map.getLayers().getArray();
            [...allLayers].forEach(l => {
                if (l?.get("layerName") === 'rangeDisplayIcon')
                    map.removeLayer(l);
            })
        }
    }, [ypType, map, radius, item])
    useEffect(() => {
        
        item && JcyjApi.YqDetail_datafindby(params).then(resp => {
            //console.log('resp',resp)
            // setData(resp.rows)
            // setTotal(resp?.total)
           
            // setJcdata(e => ({
            //     ...e,
            //     XName: resp.rows.map(e => e.updateTime.substring(8, 10)),
            //     data: [resp.rows.map(e => e.rjyl), resp.rows.map(e => e.sdjyl)],
            //     Line: ['日降雨量', '时段降雨量'],
            //     //color:'',
            // }));
            //console.log("监测数据",resp.rows)
            setJcDates(e => ({ ...e, data: resp.rows }))
            setJcDates(e => ({ ...e, item: item }))


        })
    }, [item, params, setJcDates])


    //站点切换更新站点id
    useEffect(() => {
        const arrDistrict=['叙州','翠屏','南溪','屏山','兴文','筠连','珙县','长宁','高县','江安']
        if(item?.zdm){
            const a=arrDistrict.map((e,index)=>{
                const ea=new RegExp(e);
                    if(ea.test(item?.zdm)){
                        console.log('2',)
                        if(index===0){setParams(e => ({ ...e, qx: '叙州区' }))}
                        else if(index===1){setParams(e => ({ ...e, qx: '翠屏区' }))}
                        else if(index===2){setParams(e => ({ ...e, qx: '南溪区' }))}
                        else if(index===3){setParams(e => ({ ...e, qx: '屏山线' }))}
                        else if(index===4){setParams(e => ({ ...e, qx: '兴文县' }))}
                        else if(index===5){setParams(e => ({ ...e, qx: '筠连县' }))}
                        else if(index===6){setParams(e => ({ ...e, qx: '珙县' }))}
                        else if(index===7){setParams(e => ({ ...e, qx: '长宁县' }))}
                        else if(index===8){setParams(e => ({ ...e, qx: '高县' }))}
                        else if(index===9){setParams(e => ({ ...e, qx: '江安县' }))}
                    }
            return null;
        })
        }
        
        setParams(e => ({ ...e, zdid: item.zdid }))
    }, [item])

    

    useEffect(() => {
        
        FetchHelper.getJson(`/admin-api/ybyj/rysdsc/list`,params).then(resp=>{
            setData(resp.rows)
            setTotal(resp?.total)
            // console.log('3',resp.rows.map(e => {
                
            //     return e?.tm
            // }) ,resp.rows.map(e => {
            //         const a=e?.tm.indexOf("日")
            //         //const b=e?.tm.indexOf("-")
            //         return e?.tm.substring(0,a)
            //     }))
             //为图表LineChart处理数据
            /* XName: [],横坐标内容
                data:[[折现数据点，一个数组一条线，数据个数与横坐表对应],[],...,],
                Line:[],图例，一条折线图，一个图列
                color:[], 折线颜色，一条折现一个颜色*/
            setJcdata(e => ({
                ...e,
                XName: resp.rows.map(e => {
                    const a=e?.tm.indexOf("日")
                    //const b=e?.tm.indexOf("-")
                    //return e?.tm.substring(a+1,b)
                    return e?.tm.substring(0,a)
                }),
                data: [resp.rows.map(e => e?.data)],
                Line: ['降雨量'],
                //color:'',
            }));
        })
    }, [params])



    return item ? <PanelRight>
        <div style={{
            width: 350,
            position: "absolute",
            right: 30,
            top: 30,
            bottom: 30,
            background: 'rgba(1,15,31,0.5)',
            // border: '1px solid rgba(9,107,225,0.8)',
            pointerEvents: 'auto',
            overflow: "auto",
            borderRadius: 8,
            zIndex: 2
        }} className="layout-v">
            <div style={{
                fontSize: 20,
                fontWeight: "bold",
                marginBottom: 12
            }} className='layout-h center'>
                <div className='fill w0'>
                    <div style={{
                        background: `url(${resourcePath.blockTitleBg})`,
                        height: 36,
                        backgroundSize: '100% 100%',
                        fontSize: 18,
                        lineHeight: '36px',
                        paddingLeft: 12,
                        fontWeight: "bold",
                        overflow: "hidden"
                        // overflowY: "auto",
                        // whiteSpace:'nowrap'
                    }} title={item?.zdm}>
                         {
                            item?.zdm.length > 18 ? (<span className='animate' key={props.detailItem?.id}>{item?.zdm || '水库详情'}</span>) : (<span>{item?.zdm}</span>)
                        }
                    </div>
                </div>
                <div>
                    <Button size="small" icon={<CloseOutlined />} style={{
                        // color: "#fff"
                    }} onClick={e => {
                        props.onClose?.()
                    }} />
                </div>
            </div>
            <div className='fill h0 layout-v '>
                <div className='fill  layout-v'>
                    <LittleTitle>
                        <div className='layout-h center' style={{
                            justifyContent: 'space-between',
                            paddingRight: 8,

                        }}>
                            <div>雨情数据</div>
                            <div>
                                <Radio.Group size='small' value={currentPanel} onChange={handlePanelChange}>
                                    <Radio.Button value={1}>监测数据</Radio.Button>
                                    <Radio.Button value={2}>折线图</Radio.Button>
                                    <Radio.Button value={3}>视频监测</Radio.Button>
                                </Radio.Group>
                            </div>
                        </div>
                    </LittleTitle>

                    <div  style={{
                        padding: 12,
                        // overflow:'auto'
                    }} ref={rootRef}>
                        {currentPanel === 1 &&  <ScrollTable parentNode={rootRef.current} size='small' bordered columns={[{
                                title: '开始时间',
                                dataIndex: 'begin',
                                render: (text) => (
                                    <Tooltip title={text}>
                                        <div style={{ width: '100px', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
                                            {text}
                                        </div>
                                    </Tooltip>
                                )
                            }, {
                                title: '结束时间',
                                dataIndex: 'end',
                                render: (text) => {
                                    return text;
                                }
                            }, {
                                title: '降雨量',
                                dataIndex: 'data',
                                render: (text) => {
                                    return text;
                                }
                            }]}
                                dataSource={data}
                                pagination={{
                                    current: params.pageNum,
                                    pageSize: params.pageSize,
                                    simple: true,
                                    total,
                                    onChange: (page) => {
                                        setParams(params => {
                                            return {
                                                ...params,
                                                pageNum: page
                                            }
                                        })
                                    }
                                }}
                            />}
                        {currentPanel === 2 && <LineChart jcdata={jcdata} jjz={item} />}
                        {currentPanel === 3 && <VideoMonitor/> }
                        {/* <Tabs items={[{
                            key: '1',
                            label: '监测数据',
                            children: <ScrollTable parentNode={rootRef.current} size='small' bordered columns={[{
                                title: '时段',
                                dataIndex: 'sd',
                                render: (text) => (
                                    <Tooltip title={text}>
                                        <div style={{ width: '100px', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
                                            {text}
                                        </div>
                                    </Tooltip>
                                )
                            }, {
                                title: '时段降雨量',
                                dataIndex: 'sdjyl',
                                render: (text) => {
                                    return text;
                                }
                            }, {
                                title: '日降雨量',
                                dataIndex: 'rjyl',
                                render: (text) => {
                                    return text;
                                }
                            }]}
                                dataSource={data}
                                pagination={{
                                    current: params.pageNum,
                                    pageSize: params.pageSize,
                                    simple: true,
                                    total,
                                    onChange: (page) => {
                                        setParams(params => {
                                            return {
                                                ...params,
                                                pageNum: page
                                            }
                                        })
                                    }
                                }}
                            />
                        },
                        {
                            key: '2',
                            label: '折线图',
                            children: <div><LineChart jcdata={jcdata} jjz={item} /></div>,
                        }]} /> */}


                    </div>
                    
                </div>
                <div className='fill layout-v'>
                    <LittleTitle >
                        <div className='layout-h center' style={{
                            justifyContent: "space-between",
                            paddingRight: 8
                        }}>
                            <div>研判分析</div>
                            <div>
                                <Radio.Group size="small" value={ypType} onChange={e => {
                                    setYpType(e.target.value)
                                }} buttonStyle="solid">
                                    <Radio.Button value={1}>影响范围</Radio.Button>
                                    <Radio.Button value={2}>救援保障</Radio.Button>
                                </Radio.Group>
                            </div>
                        </div>
                    </LittleTitle>
                    <div className='fill h0 layout-v' style={{
                        padding: 12
                    }}>
                        <Space style={{
                            whiteSpace:'nowrap'
                        }}>
                            <Radio.Group size='small' value={radius} onChange={e => {
                                setRadius(e.target.value)
                            }} buttonStyle="solid">
                                <Radio.Button value={5}>5km</Radio.Button>
                                <Radio.Button value={10}>10km</Radio.Button>
                                <Radio.Button value={15}>15km</Radio.Button>
                                <Radio.Button value={20}>20km</Radio.Button>
                            </Radio.Group>

                            <InputNumber size='small' placeholder='其它数值' addonAfter={"km"} style={{
                                width: 120
                            }} onChange={value => {
                                setRadius(value)
                            }} />
                        </Space>
                        <div className='fill' style={{
                            paddingTop: 12
                        }}>

                            <Table size='small' bordered columns={[{
                                title: '影响机构',
                                ellipsis:true,
                                width:180,
                                dataIndex: 'name'
                            }, {
                                title: '影响数量',
                                dataIndex: 'count',
                                align: "right",
                                render: (text) => {
                                    return text + '处'
                                }
                            }, {
                                render: (text, record) => {
                                    return <Button type="link" size="small" style={{
                                        padding: 0
                                    }} onClick={() => handleButtonClick(record)}>详情</Button>
                                }
                            }]}
                                showHeader={false}
                                dataSource={yxList} />
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </PanelRight> : null;
}